//
//  MAADMnager.m
//  MateAdv
//
//  Created by 茶 on 2023/9/20.
//

#import "MAADManager.h"
#import "MAADModel.h"
#import "MANavViewController.h"

#import <BUAdSDK/BUAdSDK.h>

@interface MAADManager () <BUSplashAdDelegate, BUNativeExpressFullscreenVideoAdDelegate, BUNativeExpressRewardedVideoAdDelegate, BUNativeExpressBannerViewDelegate>

@property (nonatomic, strong) MAADModel *model;
@property (nonatomic, assign, readwrite) BOOL isOpeningShow;


@property (nonatomic, strong) BUSplashAd *splashAd; // 开屏
@property (nonatomic, strong) BUNativeExpressFullscreenVideoAd *fullscreenAd; //插屏
@property (nonatomic, strong) BUNativeExpressRewardedVideoAd *rewardedAd; //激励
@property (nonatomic, strong) BUNativeExpressBannerView *bannerView;


@end

@implementation MAADManager

- (MAADModel *)model {
    NSDictionary *dic = [MAUserObj(kAppInfo) objectForKey:@"ad"];
    _model =  [MAADModel yy_modelWithDictionary:dic];
    return _model;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _isOpeningShow = NO;
    }
    return self;
}

- (void)initADManager {
    if (!MAUserObj(kADAppIDKey)) {
        [kUserDefaults setObject:@"5434940" forKey:kADAppIDKey];
        [kUserDefaults setObject:@"888521571" forKey:kADOpeningKey];
        [kUserDefaults setObject:@"953687216" forKey:kADBanerKey];
        [kUserDefaults setObject:@"953687218" forKey:kADPopKey];
        [kUserDefaults setObject:@"953687221" forKey:kADVideoKey];
    }
    if (MAUserObj(kAppInfo)) {
        [kUserDefaults setObject:self.model.open_screen.item.firstObject.identifier forKey:kADOpeningKey];
        [kUserDefaults setObject:self.model.plate.item.firstObject.identifier forKey:kADBanerKey];
        [kUserDefaults setObject:self.model.home_screen.item.firstObject.identifier forKey:kADPopKey];
        [kUserDefaults setObject:self.model.stimulate.item.firstObject.identifier forKey:kADVideoKey];
    }
    
    if (kUserModel.vipStatus == 0) {
        BUAdSDKConfiguration *configuration = [BUAdSDKConfiguration configuration];
        configuration.appID = MAUserObj(kADAppIDKey);//除appid外，其他参数配置按照项目实际需求配置即可。
        [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //请求广告逻辑处理
                    if (MAUserBool(kNotFirstLaunch)) {
                        [self openADEvent];
                    } else {
                        [kUserDefaults setBool:YES forKey:kNotFirstLaunch];
                    }
                });
            }
        }];
    }
}

- (void)openADEvent {
    if (!_splashAd && kUserModel.userToken && kUserModel.vipStatus == 0) {
        _isOpeningShow = YES;
        _splashAd = [[BUSplashAd alloc] initWithSlotID:MAUserObj(kADOpeningKey) adSize:ScreenBoundsSize];
        // 设置开屏广告代理
        _splashAd.delegate = self;
        _splashAd.tolerateTimeout = 3;
        // 加载广告
        [_splashAd loadAdData];
    }
}

- (void)fullScreenADEvent {
    if (!_fullscreenAd && kUserModel.userToken && kUserModel.vipStatus == 0) {
        _fullscreenAd = [[BUNativeExpressFullscreenVideoAd alloc] initWithSlotID:MAUserObj(kADPopKey)];
        _fullscreenAd.delegate = self;
        [_fullscreenAd loadAdData];
    }
}

- (void)rewardAdEvent {
    if (!_rewardedAd && kUserModel.userToken && kUserModel.vipStatus == 0) {
        [SVProgressHUD show];
        BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
        model.userId = kUserModel.userID;
        self.rewardedAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:MAUserObj(kADVideoKey) rewardedVideoModel:model];
        self.rewardedAd.delegate = self;
        // optional
        [self.rewardedAd loadAdData];
        [self showRewardVideoAd];
    }
}

- (void)bannerAdEvent {
    if (!_bannerView && kUserModel.userToken && kUserModel.vipStatus == 0) {
        UIWindow *window = nil;
        if ([[UIApplication sharedApplication].delegate respondsToSelector:@selector(window)]) {
            window = [[UIApplication sharedApplication].delegate window];
        }
        if (![window isKindOfClass:[UIView class]]) {
            window = [UIApplication sharedApplication].keyWindow;
        }
        if (!window) {
            window = [[UIApplication sharedApplication].windows objectAtIndex:0];
        }
        CGFloat bottom = 0.0;
        if (@available(iOS 11.0, *)) {
            bottom = window.safeAreaInsets.bottom;
        } else {
            // Fallback on earlier versions
        }
        MANavViewController *controller = (MANavViewController *)kKeyWindow.rootViewController;
        CGFloat bannerHeight = MARatioWidth(75);
        CGFloat bannerWidth = MARatioWidth(300);
        
        self.bannerView = [[BUNativeExpressBannerView alloc] initWithSlotID:MAUserObj(kADBanerKey) rootViewController:controller.qmui_rootViewController adSize:CGSizeMake(bannerWidth, bannerHeight)];
        self.bannerView.frame = CGRectMake((controller.view.width - bannerWidth) / 2, controller.view.height-bannerHeight, bannerWidth, bannerHeight);
        self.bannerView.delegate = self;
        [self.bannerView loadAdData];
    }
}

#pragma mark -- private method
- (void)showRewardVideoAd {
    if (_rewardedAd) {
        [SVProgressHUD dismiss];
        [self.rewardedAd showAdFromRootViewController:UIWindow.currentViewController];
    }
}

- (void)showBanner {
    if (_bannerView) {
        UIViewController *controller = UIWindow.currentViewController;
        [controller.view addSubview:_bannerView];
    }
}
#pragma mark - BUSplashAdDelegate

- (void)splashAdDidClick:(nonnull BUSplashAd *)splashAd { 
    
}

- (void)splashAdDidClose:(nonnull BUSplashAd *)splashAd closeType:(BUSplashAdCloseType)closeType {
    MABlock(self.openClose);
    self.isOpeningShow = NO;
}

- (void)splashAdDidShow:(nonnull BUSplashAd *)splashAd {
    
}

- (void)splashAdLoadFail:(nonnull BUSplashAd *)splashAd error:(BUAdError * _Nullable)error { 
    MABlock(self.openClose);
    self.isOpeningShow = NO;
}

- (void)splashAdLoadSuccess:(nonnull BUSplashAd *)splashAd { 
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [splashAd showSplashViewInRootViewController:keyWindow.rootViewController];
}

- (void)splashAdRenderFail:(nonnull BUSplashAd *)splashAd error:(BUAdError * _Nullable)error { 
    MABlock(self.openClose);
    self.isOpeningShow = NO;
}

- (void)splashAdRenderSuccess:(nonnull BUSplashAd *)splashAd { 
    
}

- (void)splashAdViewControllerDidClose:(nonnull BUSplashAd *)splashAd { 
    
}

- (void)splashAdWillShow:(nonnull BUSplashAd *)splashAd { 
    
}

- (void)splashDidCloseOtherController:(nonnull BUSplashAd *)splashAd interactionType:(BUInteractionType)interactionType { 
    
}

- (void)splashVideoAdDidPlayFinish:(nonnull BUSplashAd *)splashAd didFailWithError:(nonnull NSError *)error { 
    
}

#pragma mark - BUNativeExpressFullscreenVideoAdDelegate
- (void)nativeExpressFullscreenVideoAdDidDownLoadVideo:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd {
//回调后再去展示广告，可保证播放和展示效果
    if (_fullscreenAd) {
       [_fullscreenAd showAdFromRootViewController:UIWindow.currentViewController];
    }
}
- (void)nativeExpressFullscreenVideoAdDidClose:(BUNativeExpressFullscreenVideoAd *)fullscreenVideoAd {
    _fullscreenAd = nil;
}

#pragma mark - BUNativeExpressRewardedVideoAdDelegate
- (void)nativeExpressRewardedVideoAdDidDownLoadVideo:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd {
 //在此回调方法后进行广告的展示，可保证播放流畅和展示流畅，用户体验更好。
}

- (void)nativeExpressRewardedVideoAdServerRewardDidSucceed:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify {
    if (verify) {
        MABlock(_rewardSuccess);
    }
}

#pragma mark - BUNativeExpressBannerViewDelegate

- (void)nativeExpressBannerAdViewRenderSuccess:(BUNativeExpressBannerView *)bannerAdView {
    [self showBanner];
}

@end
